package spring.chatroom.java_chatroom.common.handler;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import spring.chatroom.java_chatroom.common.utils.JWTUtil;


@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

//    //他会自动的根据SessionId来获取到对饮的Session
//    @Autowired
//    HttpSession session;

    //这里校验是否登录过了
    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        try {
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("jwt-token") && JWTUtil.parseToken(cookie.getValue()) != null) {
                    return true;
                }
            }

            log.info("jwt 校验未通过 未登录 {}",request.getRequestURI());
            response.setStatus(406);
            return false;
        } catch (Exception e) {
            response.setStatus(406);
            return false;
        }

    }
}
